<?php

/*----------------------------*/
function dk_do_geocoding($address,$sl_id='') {    
    global $wpdb, $slplus_plugin;    
    
    // Initialize delay in geocode speed
    $delay = 0;
    
    $base_url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false";
    
    // Loop through for X retries
    //
    $iterations = get_option(SLPLUS_PREFIX.'-goecode_retries');
    if ($iterations <= 0) { $iterations = 1; }
    while($iterations){
    	$iterations--;     
    
        // Iterate through the rows, geocoding each address
        $request_url = $base_url . "&address=" . urlencode($address);
        
        if (extension_loaded("curl") && function_exists("curl_init")) {
                $cURL = curl_init();
                curl_setopt($cURL, CURLOPT_URL, $request_url);
                curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);
                $json = curl_exec($cURL);
                curl_close($cURL);  
        }else{
             $json = file_get_contents($request_url) or die("url not loading");
        }
        $json = json_decode($json);
        $status = $json->{'status'};
        
        // Geocode completed successfully
        //
        if (strcmp($status, "OK") == 0) {
            $iterations = 0;      // Break out of retry loop if we are OK
            
            // successful geocode
            $geocode_pending = false;
            $lat = $json->results[0]->geometry->location->lat;
            $lng = $json->results[0]->geometry->location->lng;
            // Update newly inserted address
            //
            if ($sl_id=='') {
                $query = sprintf("UPDATE " . $wpdb->prefix ."store_locator " .
                       "SET sl_latitude = '%s', sl_longitude = '%s' " .
                       "WHERE sl_id = LAST_INSERT_ID()".
                       " LIMIT 1;", 
                       mysql_real_escape_string($lat), 
                       mysql_real_escape_string($lng)
                       );
            }
            // Update an existing address
            //
            else {
                $query = sprintf("UPDATE " . $wpdb->prefix ."store_locator SET sl_latitude = '%s', sl_longitude = '%s' WHERE sl_id = $sl_id LIMIT 1;", mysql_real_escape_string($lat), mysql_real_escape_string($lng));
            }
            
            // Run insert/update
            //
            $update_result = $wpdb->query($query);
            if (!$update_result) {
                echo sprintf(__("Could not add/update address.  Error: %s.", SLPLUS_PREFIX),mysql_error())."\n<br>";
            }

        // Geocoding done too quickly
        //
        } else if (strcmp($status, "OVER_QUERY_LIMIT") == 0) {
            
          // No iterations left, tell user of failure
          //
	      if(!$iterations){
            echo sprintf(__("Address %s <font color=red>failed to geocode</font>. ", SLPLUS_PREFIX),$address);
            echo sprintf(__("Received status %s.", SLPLUS_PREFIX),$status)."\n<br>";
	      }                       
          $delay += 100000;

        // Invalid address
        //
        } else if (strcmp($status, 'ZERO_RESULTS') == 0) {
	    	$iterations = 0; 
	    	echo sprintf(__("Address %s <font color=red>failed to geocode</font>. ", SLPLUS_PREFIX),$address);
	      	echo sprintf(__("Unknown Address! Received status %s.", SLPLUS_PREFIX),$status)."\n<br>";
          
        // Could Not Geocode
        //
        } else {
            $geocode_pending = false;
            echo sprintf(__("Address %s <font color=red>failed to geocode</font>. ", SLPLUS_PREFIX),$address);
            echo sprintf(__("Received status %s.", SLPLUS_PREFIX),$status)."\n<br>";
        }
        usleep($delay);
    }
}    

//get member id
function dk_get_e_member_id(){
	global $auth;
	return $member_id = $auth->getUserInfo('member_id');
}

//get e-member role
function dk_get_e_member(){
	global $auth;
	global $emember_config;
	$all_levels = dbAccess::findAll(WP_EMEMBER_MEMBERSHIP_LEVEL_TABLE, ' id != 1 ', ' id DESC ');
	$member_id = $auth->getUserInfo('member_id'); 
	$editingrecord = dbAccess::find(WP_EMEMBER_MEMBERS_TABLE_NAME, ' member_id=' . $member_id);
	$user_role = 'nomember';
	
	
	foreach($all_levels as $level){
		if($editingrecord->membership_level ===$level->id){
			if($level->alias == 'Book Club')
				return $user_role = $level->alias;
			elseif($level->alias == 'Bookshop')
				return $user_role = $level->alias;
		}
	}
	
	$more_membership_arr = explode(",",$editingrecord->more_membership_levels);
	foreach($all_levels as $level){
		if(in_array($level->id ,$more_membership_arr)){	
			if($level->alias == 'Book Club')
				$user_role = $level->alias;
			elseif($level->alias == 'Bookshop')
				return $user_role = $level->alias;
		}		
	}
	return $user_role;
}

//get e-member role return array
function dk_get_e_member_arr(){
	global $auth;
	global $emember_config;
	$all_levels = dbAccess::findAll(WP_EMEMBER_MEMBERSHIP_LEVEL_TABLE, ' id != 1 ', ' id DESC ');
	$member_id = $auth->getUserInfo('member_id'); 
	$editingrecord = dbAccess::find(WP_EMEMBER_MEMBERS_TABLE_NAME, ' member_id=' . $member_id);
	$user_role_arr = array();
	
	
	foreach($all_levels as $level){
		if($editingrecord->membership_level ===$level->id){
			$user_role_arr[] = $level->alias;
		}
	}
	
	$more_membership_arr = explode(",",$editingrecord->more_membership_levels);
	foreach($all_levels as $level){
		if(in_array($level->id ,$more_membership_arr)){	
			$user_role_arr[] = $level->alias;
		}		
	}
	return $user_role_arr;
}

//create page
function dkslpCreatePage($locationID=-1)  {
            global $slplus_plugin, $wpdb;
            
            // If not licensed or incorrect location ID get out of here
            //
            if (
                !$slplus_plugin->license->packages['Store Pages']->isenabled ||
                ($locationID < 0)
                ) {
                return -1;
            } 

            // Get The Store Data
            //
            if ($store=$wpdb->get_row('SELECT * FROM '.$wpdb->prefix."store_locator WHERE sl_id = $locationID", ARRAY_A)) {            
                
                $slpStorePage = get_post($store['sl_linked_postid']);
                if (empty($slpStorePage->ID)) {
                    $store['sl_linked_postid'] = -1;
                }
				
                
				
                // Create the page
                //
                $slpNewListing = array(
                    'ID'            => (($store['sl_linked_postid'] > 0)?$store['sl_linked_postid']:''),
                    'post_type'     => 'member_pages',
                    'post_status'   => 'publish',
                    'post_title'    => $store['sl_store'],
                    'post_content'  => call_user_func(array('SLPlus_AdminUI','slpCreatePageContent'),$store),
                    );
                return wp_insert_post($slpNewListing);
             }                
}